/*
 * Copyright 2004 original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jbfilter.jsp;

import java.util.EnumSet;
import java.util.Set;

import javax.servlet.jsp.JspException;

public class EnumUtils {
	private static String getIncorrectValueMess() {
		return "Incorrect value '%s' for %s attribute in tag %s. Possible values are %s.";
	}
	public static <T extends Enum<T>> T fromString(
			String name,
			Class<T> enumType,
			Set<T> allowedValues,
			JbfilterTagAttribute attr,
			JbfilterTag tag) throws JspException {

		T t = fromString(name, enumType, attr, tag);
		if (!allowedValues.contains(t)) {
			throw new JspException(
					String.format(
							getIncorrectValueMess(),
							name,
							String.valueOf(attr),
							String.valueOf(tag),
							allowedValues));
		}
		return t;
	}
	public static <T extends Enum<T>> T fromString(
			String name,
			Class<T> enumType,
			JbfilterTagAttribute attr,
			JbfilterTag tag) throws JspException {
		try {
			
			if (name == null) {
				throw new NullPointerException(
						String.format("Value of %s attribute evaluates to null in tag %s.",
								String.valueOf(attr),
								String.valueOf(tag)));
			}
			try {
				return Enum.valueOf(enumType, name);	
			} catch (IllegalArgumentException e) {
				throw new JspException(
						String.format(
								getIncorrectValueMess(),
								name,
								String.valueOf(attr),
								String.valueOf(tag),
								EnumSet.allOf(enumType)));
			}
			
		} catch (Exception e) {
			throw new JspException(e.getMessage());
		}
	}

	// TODO unit test
	public static void main(String[] args) throws JspException {
//		EnumUtils.fromString(null, Scope.class, JbfilterTagAttribute.scope, JbfilterTag.doFilter);
//		EnumUtils.fromString("xxx", Scope.class, JbfilterTagAttribute.scope, JbfilterTag.doFilter);
		EnumUtils.fromString("page", Scope.class, EnumSet.of(Scope.session, Scope.request), JbfilterTagAttribute.scope, JbfilterTag.doFilter);
	}

}
